package com.saturn.titan.web.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.mapper.JsonMapper;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.saturn.titan.core.bean.DatatableBean;
import com.saturn.titan.core.bean.RechargeRecord;
import com.saturn.titan.core.bean.base.GroupByInfo;
import com.saturn.titan.core.bean.extend.RechargeRecordQuery;
import com.saturn.titan.core.datatable.DatatableRequest;
import com.saturn.titan.core.datatable.DatatableRequestBean;
import com.saturn.titan.core.service.ReportService;
import com.saturn.titan.util.DateUtil;
import com.saturn.titan.util.ExportUtil;

/**
 * @author liuwenhao
 */
@Controller
@RequestMapping(value = "/report")
public class ReportController {

	private static JsonMapper mapper = new JsonMapper();
	
	@Autowired
	private ReportService reportService;
	
	@Autowired
	private ExportUtil exportUtil;
	
	
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String index(Model model) throws ParseException {
		return "report/rechargeLog";
	}
	
	@RequestMapping(value = "findRechargeRecord", method = RequestMethod.POST)
	@ResponseBody
	public String findRechargeRecord_POST(
			@DatatableRequest(searchConditionClass=RechargeRecordQuery.class) DatatableRequestBean<RechargeRecordQuery> request
			) throws ParseException {
		DatatableBean<RechargeRecord> result = DatatableBean.getInstance(RechargeRecord.class);
		result.setAaData(reportService.findRechargeRecord(request.getSearchBean()));
		result.setiTotalDisplayRecords(reportService.findRechargeRecordCount(request.getSearchBean()));
		
		return mapper.toJson(result);
	}
	
	@RequestMapping(value = "getAllShopName", method = RequestMethod.GET)
	@ResponseBody
	public String findRechargeRecord_POST() throws ParseException {
		return mapper.toJson(reportService.getAllShopName());
	}
	
	@RequestMapping(value = "findRechargeRecord", method = RequestMethod.GET)
	@ResponseBody
	public String findRechargeRecord_GET(
			@DatatableRequest(searchConditionClass=RechargeRecordQuery.class) DatatableRequestBean<RechargeRecordQuery> request
			) throws ParseException {
		
		DatatableBean<RechargeRecord> result = DatatableBean.getInstance(RechargeRecord.class);
		
		RechargeRecordQuery condition = request.getSearchBean();
		if(condition == null){
			condition = new RechargeRecordQuery();
			request.setSearchBean(condition);
		}
		condition.setStart(request.getStart());
		condition.setLimit(request.getLength());
		condition.setOrderby(request.getOrder());
		
		
		
		result.setAaData(reportService.findRechargeRecord(condition));
		result.setiTotalDisplayRecords(reportService.findRechargeRecordCount(condition));
		result.setExportRequestJson(mapper.toJson(request));
		
		//获取充值总额、奖励总额、平均折扣
		GroupByInfo info = new GroupByInfo();
		info.setGroupBy(Lists.newArrayList("version"));
		info.setSumColumn(Lists.newArrayList("cRemain","cRemainBefore","cRemainAfter"));
		condition.setGroupBy(info);
		condition.setOrderby(null);
		condition.setStart(null);
		condition.setLimit(null);
		List<RechargeRecord> rechargeTotal = reportService.findRechargeRecord(condition);
		Map<String,Object> otherTotalInfo = Maps.newHashMap();
		if(!rechargeTotal.isEmpty()){
			otherTotalInfo.put("remainTotal", rechargeTotal.get(0).getRemain());
			BigDecimal a = new BigDecimal(rechargeTotal.get(0).getRemain());
			BigDecimal b = new BigDecimal(rechargeTotal.get(0).getRemainAfter());
			BigDecimal c = new BigDecimal(rechargeTotal.get(0).getRemainBefore());
			DecimalFormat myformat= new DecimalFormat("0.00");
			otherTotalInfo.put("rewordTotal", myformat.format(b.subtract(c).subtract(a))+" ");
			
			otherTotalInfo.put("persent", myformat.format(a.multiply(new BigDecimal(100)).divide(b.subtract(c),6)));
			result.setOtherTotalInfo(otherTotalInfo);
		}
		return mapper.toJson(result);
	}
	
	@RequestMapping(value = "exportRechargeLog")
	public void exportRechargeLog(@RequestParam(value = "exportRequestJson", required = false)String datatrequest,HttpServletRequest request, HttpServletResponse response) {
		DatatableRequestBean<RechargeRecordQuery> bean = mapper.fromJson(datatrequest,mapper.getMapper().getTypeFactory().constructType(new TypeReference<DatatableRequestBean<RechargeRecordQuery>>(){}));
		RechargeRecordQuery c = null;
		if(bean == null || bean.getSearchBean() == null){
			c = new RechargeRecordQuery();
		}else{
			c = bean.getSearchBean();
		}
		
		c.setStart(null);
		c.setLimit(null);
		List<RechargeRecord> result = reportService.findRechargeRecord(c);
		
		Map<String,Object> map = Maps.newHashMap();
		map.put("data", result);
		
		exportUtil.exportExcel(response, "exportRechargeLog.ftl", "rechargeLog","csv", map);
		
	}
	
	/**导出各门店的平均折扣信息*/
	@RequestMapping(value = "exportRechargePencent")
	public void exportRechargePencent(@RequestParam(value = "exportPensentRequestJson", required = false)String exportPensentRequestJson,HttpServletRequest request, HttpServletResponse response) {
		DatatableRequestBean<RechargeRecordQuery> bean = mapper.fromJson(exportPensentRequestJson,mapper.getMapper().getTypeFactory().constructType(new TypeReference<DatatableRequestBean<RechargeRecordQuery>>(){}));
		RechargeRecordQuery c = null;
		if(bean == null || bean.getSearchBean() == null){
			c = new RechargeRecordQuery();
		}else{
			c = bean.getSearchBean();
		}
		
		c.setStart(null);
		c.setLimit(null);
		GroupByInfo info = new GroupByInfo();
		info.setGroupBy(Lists.newArrayList("shopName"));
		info.setSumColumn(Lists.newArrayList("cRemain","cRemainBefore","cRemainAfter"));
		c.setGroupBy(info);
		List<RechargeRecord> result = reportService.findRechargeRecord(c);
		
		if(!result.isEmpty()){
			List<Map<String,String>> resultFlt = Lists.newArrayList();
			for(RechargeRecord r : result){
				Map<String,String> tmp = Maps.newHashMap();
				BigDecimal aa = new BigDecimal(r.getRemain());
				BigDecimal bb = new BigDecimal(r.getRemainAfter());
				BigDecimal cc = new BigDecimal(r.getRemainBefore());
				DecimalFormat myformat= new DecimalFormat("0.00");
				String remain = r.getRemain();
				String rewordTotal = myformat.format(bb.subtract(cc).subtract(aa))+" ";
				String persent = myformat.format(aa.multiply(new BigDecimal(100)).divide(bb.subtract(cc),6));
				tmp.put("name", r.getShopName());
				tmp.put("remain", remain);
				tmp.put("rewordTotal", rewordTotal);
				tmp.put("persent", persent);
				resultFlt.add(tmp);
			}
			Map<String,Object> map = Maps.newHashMap();
			map.put("data", resultFlt);
			map.put("start",DateUtil.dateTime2String(c.getDtTimeFrom()));
			map.put("end", DateUtil.dateTime2String(c.getDtTimeTo()));
			exportUtil.exportExcel(response, "exportRechargePersent.ftl", "门店平均折扣","csv", map);
		}
		
	}
	
}

